package com.software.loginregister.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.software.loginregister.R;
import com.software.loginregister.activity.RecommendDetailActivity;
import com.software.loginregister.entity.Works;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HotFoodAdapter extends RecyclerView.Adapter<HotFoodAdapter.ViewHolder> {
    private List<Map<String, Object>> hotWorks;

    public HotFoodAdapter(List<Map<String, Object>> hotWorks) {
        this.hotWorks = hotWorks != null ? hotWorks : new ArrayList<>();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_hot_food, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Map<String, Object> work = hotWorks.get(position);

        // 设置标题
        String worksName = (String) work.get("works_name");
        holder.tvSearchHotFoodName.setText(worksName != null ? worksName : "未命名作品");

        // 设置描述
        String description = (String) work.get("description");
        holder.tvSearchHotFoodDescription.setText(description != null ? description : "暂无描述");

        // 处理点赞数
        Object likeCountObj = work.get("like_count");
        int likeCount = 0;
        if (likeCountObj instanceof Number) {
            likeCount = ((Number) likeCountObj).intValue();
        }
        holder.tvLikeCount.setText(String.format("%d 赞", likeCount));

        // 加载图片
        String photoUrl = (String) work.get("cover_image");
        if (photoUrl != null) {
            Glide.with(holder.ivSearchHotFood.getContext())
                    .load(photoUrl)
                    .placeholder(R.drawable.img_restaurant)
                    .centerCrop()
                    .into(holder.ivSearchHotFood);
        }

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            Context context = v.getContext();
            Intent intent = new Intent(context, RecommendDetailActivity.class);

            // 获取作品ID并进行空值检查
            Object worksIdObj = work.get("works_id");
            Long worksId = 0L;
            if (worksIdObj instanceof Number) {
                worksId = ((Number) worksIdObj).longValue();
            }

            Log.d("HotFoodAdapter", "作品ID: " + worksId);

            if (worksId <= 0) {
                Toast.makeText(context, "无效的作品ID", Toast.LENGTH_SHORT).show();
                return;
            }

            // 传递数据到详情页面，添加空值检查
            intent.putExtra("worksId", worksId);
            intent.putExtra("worksName", worksName);
            intent.putExtra("photoUrl", photoUrl);
            intent.putExtra("description", description);

            // 修改：获取用户ID并转换为int类型
            Object userIdObj = work.get("user_id");
            int userId = -1;  // 默认值使用int
            if (userIdObj instanceof Number) {
                // 确保不会超出int范围
                long longUserId = ((Number) userIdObj).longValue();
                if (longUserId <= Integer.MAX_VALUE && longUserId >= Integer.MIN_VALUE) {
                    userId = (int) longUserId;
                }
            }

            Log.d("HotFoodAdapter", "用户ID: " + userId);
            intent.putExtra("userId", userId);  // 传递int类型的userId

            // 获取用户名并进行空值检查
            String userName = (String) work.get("user_name");
            intent.putExtra("nickname", userName != null ? userName : "");

            context.startActivity(intent);
        });
    }

    // 在updateData方法中添加日志
    public void updateData(List<Map<String, Object>> newWorks) {
        Log.d("HotFoodAdapter", "更新数据列表大小: " + (newWorks != null ? newWorks.size() : 0));
        if (newWorks != null && !newWorks.isEmpty()) {
            Map<String, Object> firstWork = newWorks.get(0);
            Log.d("HotFoodAdapter", "第一条数据内容: " + firstWork.toString());
            for (Map.Entry<String, Object> entry : firstWork.entrySet()) {
                Log.d("HotFoodAdapter", String.format("键: %s, 值: %s, 类型: %s",
                        entry.getKey(),
                        entry.getValue(),
                        entry.getValue() != null ? entry.getValue().getClass().getName() : "null"));
            }
        }
        this.hotWorks = newWorks != null ? newWorks : new ArrayList<>();
        notifyDataSetChanged();
    }

    @Override
    public int getItemCount() {
        return hotWorks != null ? hotWorks.size() : 0;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivSearchHotFood;
        TextView tvSearchHotFoodName;
        TextView tvSearchHotFoodDescription;
        TextView tvLikeCount;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivSearchHotFood = itemView.findViewById(R.id.iv_search_hot_food);
            tvSearchHotFoodName = itemView.findViewById(R.id.tv_search_hot_food_name);
            tvSearchHotFoodDescription = itemView.findViewById(R.id.tv_search_hot_food_description);
            tvLikeCount = itemView.findViewById(R.id.tv_like_count);
        }
    }
}